package com.bac.rentmap.web.controller.migrate;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.bac.rentmap.ad.flat.Constants;
import com.bac.rentmap.ad.flat.FlatAd;

public class SourceUrlMigratingController  extends AbstractController {
    private static final Logger log = Logger
            .getLogger(SourceUrlMigratingController.class.getName());
    private PersistenceManagerFactory persistenceManagerFactory;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
        try{
            List<FlatAd> flatAds = loadFlatAds(persistenceManager, Integer.parseInt(request.getParameter("page")));
            response.getWriter().write("Loaded " + flatAds.size() + " flatAds\n");
            int updatedCount = 0;
            for(FlatAd flatAd : flatAds){
                if(flatAd.getSourceUrl() == null){
                    flatAd.setSourceUrl(Constants.INTERNAL_FLAT_AD_SOURCE_URL);
                    updatedCount++;
                }
            }
            response.getWriter().write("Updated " + updatedCount + " flatAds\n");
        }
        finally{
            persistenceManager.close();
        }
        return null;
    }
    
    private List<FlatAd> loadFlatAds(PersistenceManager persistenceManager, int page) {
        Query query = persistenceManager.newQuery(FlatAd.class);
        @SuppressWarnings("unchecked")
        int pageSize = 100;
        query.setRange(page * pageSize, (page + 1) * pageSize);
        List<FlatAd> res = (List<FlatAd>) query.execute();
        log.fine("Loaded " + res.size() + " FlatAds");
        return res;
    }

    public void setPersistenceManagerFactory(
            PersistenceManagerFactory persistenceManagerFactory) {
        this.persistenceManagerFactory = persistenceManagerFactory;
    }
}
